﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization
Imports Microsoft.VisualBasic


Partial Class Interfaz_frmAdminFacturaEmitir
    Inherits System.Web.UI.Page
    Dim CL As New ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet
    Dim DataFactura As New DataSetFactura

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If
        Dim ArrayItem As New ArrayList
        Dim ArrayOrdenCompra As New ArrayList
        Dim ArrayGuiaDespacho As New ArrayList
        Dim ArrayCliente As New ArrayList
        Dim i As Integer

        ArrayItem = CL.ObtenerMaterial()
        ArrayOrdenCompra = CL.ObtenerOrdenCompra()
        ArrayGuiaDespacho = CL.obtenerGuiaDespacho()
        ArrayCliente = CL.obtenerCliente()


        If Not Page.IsPostBack Then
            For i = 0 To ArrayItem.Count - 1
                Me.DropItemEF.Items.Add(DirectCast(ArrayItem.Item(i), Material).Nombre)
            Next

            For i = 0 To ArrayOrdenCompra.Count - 1
                Me.DropOrdenCompraEF.Items.Add(DirectCast(ArrayOrdenCompra.Item(i), OrdenCompra).NumeroDeOrden)
            Next

            For i = 0 To ArrayGuiaDespacho.Count - 1
                Me.DropGuiaDespachoEF.Items.Add(DirectCast(ArrayGuiaDespacho.Item(i), GuiaDespacho).Id)
            Next

            For i = 0 To ArrayCliente.Count - 1
                Dim itemcliente As New ListItem
                itemcliente.Value = DirectCast(ArrayCliente.Item(i), Cliente).Rut
                itemcliente.Text = DirectCast(ArrayCliente.Item(i), Cliente).RznSocial
                Me.DropCliente.Items.Add(itemcliente)

            Next
        End If

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("EmiteFactura") Is Nothing Then
            Session("EmiteFactura") = dtDatos
        Else
            dtDatos = DirectCast(Session("EmiteFactura"), DataTable)

        End If

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("CODIGO"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))

                Me.GridFacturaEmitida.DataBind()
                Me.GridFacturaEmitida.DataSource = Me.dtDatos
            Catch
            End Try
        End If

        'Me.GridFacturaEmitida.DataBind()
        Me.GridFacturaEmitida.DataSource = Me.dtDatos
        Me.onEmitirFactura()

        Visualizador.Attributes.Add("onclick", "javascript:visualizadorFacturaEmitida();")
    End Sub

#Region "Funcionalidades"
    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

    Private Sub IngresarItem()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.txtCodigoEF.Text <> "" And Me.txtDetalleEF.Text <> _
            "" And Me.TxtCantidadEF.Text <> "" And Me.TxtPrecioUnitarioEF.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropItemEF.Text
                drDatos.Item("CODIGO") = Me.txtCodigoEF.Text
                drDatos.Item("DETALLE") = Me.txtDetalleEF.Text
                drDatos.Item("CANTIDAD") = Me.TxtCantidadEF.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxtPrecioUnitarioEF.Text)

                dtDatos.Rows.Add(drDatos)

                Me.GridFacturaEmitida.DataSource = dtDatos
                Me.GridFacturaEmitida.DataBind()

                Me.LimpiarItemFacturaEmitida()
                Me.GridFacturaEmitida.ForeColor = Drawing.Color.Blue
                Me.LabelAvisoEF.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAvisoEF.ForeColor = Drawing.Color.Red
                Me.LabelAvisoEF.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Public Sub meteReporte()
        Dim ruta As String = System.AppDomain.CurrentDomain.BaseDirectory()
        Dim oRep As New ReportDocument
        Dim rutaFinal As String
        Me.CargarFactura()
        rutaFinal = ruta + "App_Code\Reportes\ReporteFactura.rpt"
        oRep.Load(rutaFinal)
        oRep.SetDataSource(DataFactura)
        Session("CRFacturaEmitida") = oRep
        'CRV.ReportSource = oRep
    End Sub

    Function CargarFactura() As Boolean
        Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat
        nfi.CurrencyDecimalDigits = 0
        nfi.CurrencyGroupSeparator = "."

        Dim myRow As DataRow = Me.DataFactura.DatosCabezera.NewRow
        Dim filaGrid As GridViewRow
        Dim myFila As DataRow

        'Datos Fijos
        Dim cliente As Cliente = DirectCast(CL.obtenerCliente(DropCliente.Text).Item(0), Cliente)
        Dim Fecha As String = BasicFecha.Text
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)
        Dim iva As Integer = 0
        Dim TotalNeto As Integer = 0
        Dim TotalBruto As Integer = 0
        Dim TotalPorItem As Integer = 0

        'Declaraciones para insert a BD
        Dim ArrayItemFactura As New ArrayList

        Try

            ' Carga De Datos del Destinatario
            myRow.Item("nombre") = cliente.RznSocial
            myRow.Item("direccion") = cliente.Direccion
            myRow.Item("giro") = cliente.Giro
            myRow.Item("rut") = cliente.Rut
            myRow.Item("comuna") = cliente.Comuna
            myRow.Item("telefono") = cliente.Telefono
            myRow.Item("guiadespacho") = DropGuiaDespachoEF.Text
            myRow.Item("vendedor") = TextVendedorEF.Text
            myRow.Item("ordencompra") = DropOrdenCompraEF.Text
            myRow.Item("condventa") = TxtCondVentaEF.Text
            myRow.Item("dia") = dia
            myRow.Item("mes") = mes
            myRow.Item("año") = año

            'Suma Valores de actividades
            With Me.GridFacturaEmitida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaEmitida.Rows(fila)
                    myFila = DataFactura.DatosItem.NewRow

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    myFila.Item("factItem") = filaGrid.Cells(1).Text
                    myFila.Item("facCodigo") = filaGrid.Cells(2).Text
                    myFila.Item("factDetalle") = filaGrid.Cells(3).Text
                    myFila.Item("factCantidad") = filaGrid.Cells(4).Text
                    myFila.Item("factPrecioUnitario") = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem
                    DataFactura.DatosItem.Rows.Add(myFila)
                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With

            DataFactura.DatosCabezera.Rows.Add(myRow)

            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            TotalBruto = TotalNeto + iva

            myRow.Item("neto") = TotalNeto
            myRow.Item("iva") = iva
            myRow.Item("total") = TotalBruto

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaEmitida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxtCondVentaEF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefCliente = cliente
            nuevaFactura.Total = TotalBruto

            'CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
            Return False
        End Try
    End Function

    Private Sub IngresaFacturaBD()
        Dim filaGrid As GridViewRow

        'Datos Fijos
        Dim cliente As Cliente = DirectCast(CL.obtenerCliente(DropCliente.Text).Item(0), Cliente)
        Dim Fecha As String = BasicFecha.Text
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)
        Dim iva As Integer = 0
        Dim TotalNeto As Integer = 0
        Dim TotalBruto As Integer = 0
        Dim TotalPorItem As Integer = 0
        Dim rznSocial As String = ""
        Dim direccion As String = ""
        Dim giro As String = ""
        Dim rut As String = ""
        Dim comuna As String = ""
        Dim telefono As String = ""
        Dim guiaDespacho As String = ""
        Dim vendedor As String = ""
        Dim ordenCompra As String = ""
        Dim condVenta As String = ""
        'Detalle de items
        Dim factItem As String = ""
        Dim facCodigo As String = ""
        Dim factDetalle As String = ""
        Dim factCantidad As String = ""
        Dim factPrecioUnitario As String = ""
        'Declaraciones para insert a BD
        Dim ArrayItemFactura As New ArrayList

        Try

            'Carga De Datos del Destinatario
            rznSocial = cliente.RznSocial
            direccion = cliente.Direccion
            giro = cliente.Giro
            rut = cliente.Rut
            comuna = cliente.Comuna
            telefono = cliente.Telefono
            guiaDespacho = DropGuiaDespachoEF.Text
            vendedor = TextVendedorEF.Text
            ordenCompra = DropOrdenCompraEF.Text
            condVenta = TxtCondVentaEF.Text

            'Suma Valores de actividades
            With Me.GridFacturaEmitida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaEmitida.Rows(fila)

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    factItem = filaGrid.Cells(1).Text
                    facCodigo = filaGrid.Cells(2).Text
                    factDetalle = filaGrid.Cells(3).Text
                    factCantidad = filaGrid.Cells(4).Text
                    factPrecioUnitario = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem

                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            TotalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaEmitida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxtCondVentaEF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefCliente = cliente
            nuevaFactura.Total = TotalBruto
            CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try

    End Sub

    Private Sub llenaDatosCliente()
        Dim query As String = ""
        Dim dato As String = ""

        Dim Arraycliente As ArrayList = CL.obtenerClienteGeneral(DropCliente.SelectedValue)

        txtFono.Text = DirectCast(Arraycliente.Item(0), Cliente).Telefono
        txtDireccion.Text = DirectCast(Arraycliente.Item(0), Cliente).Direccion
        txtrut.Text = DirectCast(Arraycliente.Item(0), Cliente).Rut
        txtGiro.Text = DirectCast(Arraycliente.Item(0), Cliente).Giro
        txtComuna.Text = DirectCast(Arraycliente.Item(0), Cliente).Comuna
        txtCiudad.Text = DirectCast(Arraycliente.Item(0), Cliente).Ciudad
    End Sub

    Public Sub offEmitirFactura()
        Me.PanelEmitirFactura.Visible = False

    End Sub

    Public Sub onEmitirFactura()
        Me.PanelEmitirFactura.Visible = True
    End Sub

    Private Sub LimpiarItemFacturaEmitida()
        txtCodigoEF.Text = String.Empty
        txtDetalleEF.Text = String.Empty
        TxtCantidadEF.Text = String.Empty
        TxtPrecioUnitarioEF.Text = String.Empty
        TextVendedorEF.Text = String.Empty
        TxtCondVentaEF.Text = String.Empty
    End Sub

    Private Sub LimpiarTodoFacturaEmitida()
        LimpiarItemFacturaEmitida()
        txtrut.Text = String.Empty
        txtDireccion.Text = String.Empty
        txtrut.Text = String.Empty
        txtFono.Text = String.Empty
        txtGiro.Text = String.Empty
        txtComuna.Text = String.Empty
        txtCiudad.Text = String.Empty

        Me.GridFacturaEmitida.DataSource = Nothing
        Me.GridFacturaEmitida.DataBind()
    End Sub

    Private Sub LimpiarDataGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

#End Region

#Region "Eventos Grid"
    'Grid Material
    Protected Sub GridFacturaEmitida_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridFacturaEmitida.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridFacturaEmitida.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridFacturaEmitida.EditIndex = -1
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("EmiteFactura"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridFacturaEmitida.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = cantidad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridFacturaEmitida.EditIndex = -1

        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Sub GridFacturaEmitida_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("EmiteFactura"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridFacturaEmitida.DataSource = dt
        GridFacturaEmitida.DataBind()
    End Sub
#End Region

#Region "Botones"

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        LimpiarTodoFacturaEmitida()
    End Sub

    Protected Sub Visualizador_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Visualizador.Click
        meteReporte()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        IngresarItem()
    End Sub

    Protected Sub BtnBuscar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscar.Click
        llenaDatosCliente()
    End Sub

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        IngresaFacturaBD()
        MsgBox("La factura a sido ingresada Exitosamente")
        LimpiarTodoFacturaEmitida()
        Me.vaciaGrid()
    End Sub
#End Region

    
    
    
End Class
